package com.jinmdz.fmis.dao.dao.provider;

import com.jinmdz.fmis.core.constant.EDictCode;
import com.jinmdz.fmis.dao.base.BaseProvider;
import com.jinmdz.fmis.dao.model.settlement.SettleDailyExpensesAllData;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;

/**
 * 日结审核Provider
 *
 * @author LiCongLu
 * @date 2020-02-21 11:19
 */
public class ChargeVerifyProvider extends BaseProvider {

    /**
     * 按照主键获取日结审核信息
     *
     * @param id 主键
     * @return
     * @author LiCongLu
     * @date 2020-02-21 17:16
     */
    public String getChargeVerifyViewById(@Param("id") Integer id) {
        return new SQL() {
            {
                StringBuilder builder = new StringBuilder();
                builder.append(" charge_verify.id,verify_batch_no,verify_charge,verify_time,invoice_count,receipt_count,verify_user_id,charge_verify.remark,charge_verify.version");
                builder.append(" ,system_user.full_name as verify_user_name");
                SELECT(builder.toString());
                FROM(" charge_verify ");
                LEFT_OUTER_JOIN(" system_user on system_user.id = charge_verify.verify_user_id  ");
                WHERE(" charge_verify.deleted = 0 ");
                WHERE(" charge_verify.id = #{id} ");
                ORDER_BY(" charge_verify.id ");
            }
        }.toString();
    }


    /**
     * 按照查询条件日结审核查询费用列表
     *
     * @param data             请求条件
     * @param invoiceStateCode 作废发票编码
     * @return
     * @author LiCongLu
     * @date 2020-02-21 16:03
     */
    public String listSettleDailyExpensesAllSettleByData(@Param("data") SettleDailyExpensesAllData data, @Param("invoiceStateCode") Integer invoiceStateCode) {
        return new SQL() {
            {
                StringBuilder builder = new StringBuilder();
                builder.append(" charge_settle.id,charge_settle.business_code,settle_batch_no,receipt_charge,discount_charge,benefit_charge,settle_charge,settle_time,settle_type_code");
                builder.append(" ,receipt_no,as_refund,as_verify,verify_id");
                builder.append(" ,settle_user_id,charge_settle.random_code,charge_settle.remark,charge_settle.version");
                builder.append(" ,settle_user.full_name as settle_user_name ");
                builder.append(" ,invoice_code,invoice_no,invoice_title");

                // 关联查询付款方式
                builder.append(" ,( select group_concat(distinct data_dictionary.data_text) from charge_settle_pay ");
                builder.append("   left join data_dictionary ON charge_settle_pay.pay_type_code = data_dictionary.data_code and data_dictionary.dict_code='" + EDictCode.PAY_TYPE.getCode() + "'");
                builder.append("   where charge_settle_pay.charge_settle_id = charge_settle.id");
                builder.append("  ) as pay_type ");

                // 逝者名字
                builder.append(" ,funeral_dead.dead_name");

                // 日结审核信息
                builder.append(" ,verify_user.full_name as verify_user_name");
                builder.append(" ,charge_verify.verify_time");
                SELECT(builder.toString());
                FROM(" charge_settle ");
                JOIN(" funeral_dead on funeral_dead.business_code = charge_settle.business_code ");
                LEFT_OUTER_JOIN(" system_user settle_user on settle_user.id = charge_settle.settle_user_id ");
                LEFT_OUTER_JOIN(" charge_verify on charge_verify.id = charge_settle.verify_id and charge_verify.deleted = 0 and charge_settle.as_verify = 1 ");
                LEFT_OUTER_JOIN(" charge_invoice on charge_invoice.id = invoice_id and invoice_state_code != #{invoiceStateCode} ");
                LEFT_OUTER_JOIN(" system_user verify_user on verify_user.id = charge_verify.verify_user_id ");
                WHERE(" charge_settle.deleted = 0 ");

                // 结算起始时间
                if (data.getSettleTimeStart() != null) {
                    WHERE(" charge_settle.settle_time >= #{data.settleTimeStart,jdbcType=TIMESTAMP} ");
                }

                // 结算结束时间
                if (data.getSettleTimeEnd() != null) {
                    WHERE(" charge_settle.settle_time <= #{data.settleTimeEnd,jdbcType=TIMESTAMP} ");
                }

                // 结算人员名称
                if (valid(data.getSettleUserName())) {
                    WHERE(" settle_user.full_name like concat('%',#{data.settleUserName},'%') ");
                }

                // 发票号片段
                if (valid(data.getInvoiceNoSegment())) {
                    String whereStr = getInvoiceNoWhere(data.getInvoiceNoSegment());
                    // 判断是否解析完成
                    if (valid(whereStr)) {
                        WHERE(" ( " + whereStr + " ) ");
                    }
                }

                // 审核状态值
                if (validAll(data.getVerifyState())) {

                    WHERE(" as_verify = #{data.verifyState,jdbcType=TINYINT} ");

                    //已审核（已审核的需要带入）
                    if (valid(data.getVerifyState())) {

                        // 日结审核批次编号段
                        if (valid(data.getVerifyBatchNo())) {
                            WHERE(" verify_batch_no like concat('%',#{data.verifyBatchNo},'%') ");
                        }

                        // 审核人员主键
                        if (valid(data.getVerifyUserId())) {
                            WHERE(" verify_user_id = #{data.verifyUserId} ");
                        }
                    }

                }

                // 收据号片段
                if (valid(data.getReceiptNoSegment())) {
                    WHERE(" receipt_no like concat('%',#{data.receiptNoSegment},'%') ");
                }

                ORDER_BY(" charge_settle.id ");
            }
        }.toString();
    }

    /**
     * 解析获取发票号查询条件
     * 举例：100001,100020-100032
     *
     * @param invoiceNoSegment 发票号段
     * @return
     * @author LiCongLu
     * @date 2020-03-06 17:05
     */
    private String getInvoiceNoWhere(String invoiceNoSegment) {
        StringBuilder builder = new StringBuilder();
        // 单独查询的分隔符
        String sole = ",";
        // 区间查询的分隔符
        String section = "-";

        // 兼容汉字编码
        invoiceNoSegment = invoiceNoSegment.replace("，", sole);

        String[] splitArray = invoiceNoSegment.split(sole);
        for (String splitTemp : splitArray) {
            if (!valid(splitTemp)) {
                continue;
            }

            // 单发票号
            if (!splitTemp.contains(section)) {
                // 拼接时后端留空格
                builder.append("or invoice_no = '" + splitTemp + "' ");
                continue;
            }

            // 发票段,例如10-15
            String[] sectionTemp = splitTemp.split(section);
            if (sectionTemp.length == 2 && valid(sectionTemp[0])
                    && valid(sectionTemp[1])) {
                // 拼接时后端留空格
                builder.append("or ( invoice_no >= '" + sectionTemp[0] + "' and invoice_no<= '" + sectionTemp[1] + "' ) ");
            }
        }

        // 当正确解析时去除第一个or
        if (builder.length() > 0) {
            String whereSql = builder.toString();
            return whereSql.substring("or".length());
        }
        return null;
    }

    /**
     * 按照查询条件日结审核查询日结审核列表
     *
     * @param data 请求条件
     * @return
     * @author LiCongLu
     * @date 2020-02-21 17:39
     */
    public String listSettleDailyExpensesAllVerifyByData(@Param("data") SettleDailyExpensesAllData data) {
        return new SQL() {
            {
                StringBuilder builder = new StringBuilder();
                builder.append(" distinct charge_verify.id,verify_batch_no,verify_charge,verify_time,invoice_count,receipt_count,verify_user_id,charge_verify.remark,charge_verify.version");
                builder.append(" ,verify_user.full_name as verify_user_name");

                SELECT(builder.toString());
                FROM(" charge_verify ");
                JOIN(" charge_settle on charge_settle.verify_id = charge_verify.id and charge_settle.deleted = 0 and charge_settle.as_verify = 1");
                LEFT_OUTER_JOIN(" system_user settle_user on settle_user.id = charge_settle.settle_user_id  ");
                LEFT_OUTER_JOIN(" system_user verify_user on verify_user.id = charge_verify.verify_user_id  ");
                WHERE(" charge_verify.deleted = 0 ");

                // 结算起始时间
                if (data.getSettleTimeStart() != null) {
                    WHERE(" charge_settle.settle_time >= #{data.settleTimeStart,jdbcType=TIMESTAMP} ");
                }

                // 结算结束时间
                if (data.getSettleTimeEnd() != null) {
                    WHERE(" charge_settle.settle_time <= #{data.settleTimeEnd,jdbcType=TIMESTAMP} ");
                }

                // 结算人员名称
                if (valid(data.getSettleUserName())) {
                    WHERE(" settle_user.full_name like concat('%',#{data.settleUserName},'%') ");
                }

                // 发票号片段
                if (valid(data.getInvoiceNoSegment())) {
                    String whereStr = getInvoiceNoWhere(data.getInvoiceNoSegment());
                    // 判断是否解析完成
                    if (valid(whereStr)) {
                        WHERE(" ( " + whereStr + " ) ");
                    }
                }

                // 收据号片段
                if (valid(data.getReceiptNoSegment())) {
                    WHERE(" receipt_no like concat('%',#{data.receiptNoSegment},'%') ");
                }

                // 日结审核批次编号段
                if (valid(data.getVerifyBatchNo())) {
                    WHERE(" verify_batch_no like concat('%',#{data.verifyBatchNo},'%') ");
                }

                // 审核人员主键
                if (valid(data.getVerifyUserId())) {
                    WHERE(" verify_user_id = #{data.verifyUserId} ");
                }

                ORDER_BY(" charge_verify.id ");
            }
        }.toString();
    }

}
